package com.woniu.controller;

import cn.hutool.captcha.LineCaptcha;
import com.github.pagehelper.PageInfo;
import com.woniu.Service.AccountService;
import com.woniu.Service.MenuService;
import com.woniu.Service.RoleService;
import com.woniu.Service.UserRoleService;
import com.woniu.annotation.CheckPermission;
import com.woniu.entity.Account;
import com.woniu.entity.Role;
import com.woniu.entity.UserRole;
import com.woniu.util.JsonResult;
import com.woniu.util.JwtUtil;
import com.woniu.vo.CodeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @Author: Gwj
 * @Date: 2024/7/1 16:35
 */
@RestController
@Slf4j
@RequestMapping("/account")
@Api(value = "用户功能接口", tags = "所有的用户功能")
public class AccountController {
    @Resource
    private AccountService accountService;

    @Resource
    private MenuService menuService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RoleService roleService;

    @Resource
    private LineCaptcha lineCaptcha;
    @Resource
    private UserRoleService userRoleService;

    @Resource
    private HashMap<String, String> map;

    /**
     * 用户登录
     *
     * @param account
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口")
    public JsonResult<Account> login(Account account, HttpServletResponse response, CodeVo codeVo) throws Exception {
        log.info("验证码ID：" + codeVo.getCodeId() + "验证码：" + codeVo.getCode() + "用户名：" + account.getAccountName() + "密码：" + account.getPassword() + "用户类别：");

        JsonResult<Account> jsonResult = new JsonResult<>();

        //从缓存中得到codeId 匹配的code进行验证
        String mapCode = map.get(codeVo.getCodeId());
        if (mapCode != null && mapCode.equalsIgnoreCase(codeVo.getCode())) {
            Account login = accountService.findAccountToLogin(account.getAccountName());
            if (login != null) {
                if (login.getPassword().equals(account.getPassword())) {
                    //判断用户的类别 00为商户用户 可以登录后台系统
                    if (login.getAccountType().equals("00")) {
                        if (login.getIsDelete() != 1) {
                            jsonResult.setMessage("登陆成功");
                            jsonResult.setCode(200);
                            //更新最后登录时间
                            accountService.upadateAccountLoginDate(login);
                            //登陆成功之后生成token
                            String token = jwtUtil.createToken(account.getAccountName());
                            log.info("生成的TOKEN：" + token);
                            //将token写入到响应头中
                            response.setHeader("authentication", token);
                            //登陆成功之后，把当前用户的权限数据缓存进redis中
                            menuService.selectMenuPermissionByAccountName(account.getAccountName());
                        } else {
                            jsonResult.setMessage("您的账号已被冻结，请联系管理员");
                            jsonResult.setCode(500);
                        }
                    } else {
                        jsonResult.setMessage("非管理员不可登录");
                        jsonResult.setCode(500);
                    }
                } else {
                    jsonResult.setMessage("密码不正确");
                    jsonResult.setCode(500);
                }
            } else {
                jsonResult.setMessage("用户名不存在");
                jsonResult.setCode(500);
            }
        } else {
            jsonResult.setMessage("验证码错误");
            jsonResult.setCode(500);
        }
        return jsonResult;
    }

    @GetMapping("/findAccountInfo")
    @ApiOperation(value = "查询单个用户")
    @CheckPermission("account:select")
    public JsonResult<Account> findAccountInfo(@RequestParam("accountName") String accountName) throws Exception {
        Account account = accountService.findAccountByName(accountName);
        if (account != null) {
            return JsonResult.build(200, "success", account);
        } else {
            return JsonResult.build(500, "查询不到此用户", null);
        }
    }

    /**
     * 修改个人密码时的密码验证
     *
     * @param accountName
     * @param password
     * @return
     * @throws Exception
     */
    @GetMapping("/checkPassword/{accountName}/{password}")
    @ApiOperation(value = "检查账号和密码是否正确")
    public JsonResult checkPassword(@PathVariable("accountName") String accountName, @PathVariable("password") String password) throws Exception {
        Account account = accountService.checkPassword(accountName, password);
        if (account != null) {
            if (account.getPassword().equals(password)) {
                return JsonResult.build(500, "新密码不能与旧密码相同", false);
            } else {
                return JsonResult.build(200, "此密码可用", true);
            }
        } else {
            return JsonResult.build(200, "此密码可用", true);
        }
    }

    /**
     * 修改个人密码
     *
     * @param accountName
     * @param password
     * @return
     * @throws Exception
     */
    @PutMapping("/updateAccountPassword")
    @ApiOperation(value = "修改用户密码")
    public JsonResult updateAccountPassword(@RequestParam("accountName") String accountName, @RequestParam("password") String password) throws Exception {
        int i = accountService.updatePassword(accountName, password);
        if (i > 0) {
            return JsonResult.build(200, "修改成功", i);
        } else {
            return JsonResult.build(500, "修改失败", i);
        }
    }


    /**
     * 所有用户的分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @GetMapping("/showAccountByPage")
    @ApiOperation(value = "查询所有用户")
    @CheckPermission("account:select")
    public JsonResult<PageInfo<Account>> showAccountByPage(@RequestParam(defaultValue = "1") int pageNum,
                                                           @RequestParam(defaultValue = "5") int pageSize) throws Exception {
        PageInfo<Account> page = accountService.findAccountByPage(pageNum, pageSize);
        return JsonResult.build(200, "success", page);
    }

    /**
     * 新增用户
     *
     * @param account
     * @return
     * @throws Exception
     */
    @PostMapping("/addAccount")
    @ApiOperation(value = "添加用户")
    @CheckPermission("account:insert")
    public JsonResult<Integer> addAccount(Account account) throws Exception {
        int i = accountService.addAccount(account);
        if (i > 0) {
            return JsonResult.build(200, "添加成功", i);
        } else {
            return JsonResult.build(500, "添加失败", i);
        }
    }

    /**
     * 删除用户 逻辑删除
     *
     * @param account
     * @return
     * @throws Exception
     */
    @PutMapping("/changeAccountIsDeleted")
    @ApiOperation(value = "删除用户")
    @CheckPermission("account:delete")
    public JsonResult<Integer> changeAccountIsDeleted(Account account) throws Exception {
        int i = accountService.changeAccountIsDeleted(account);
        if (i > 0) {
            return JsonResult.build(200, "删除成功", i);
        } else {
            return JsonResult.build(500, "删除失败", i);
        }
    }

    /**
     * 修改用户信息
     *
     * @param account
     * @return
     * @throws Exception
     */
    @PutMapping("/updateAccount")
    @ApiOperation(value = "修改用户信息")
    @CheckPermission("account:update")
    public JsonResult<Integer> updateAccount(Account account) throws Exception {
        int i = accountService.updateAccountInfoById(account);
        if (i > 0) {
            return JsonResult.build(200, "修改成功", i);
        } else {
            return JsonResult.build(500, "修改失败", i);
        }
    }

    /**
     * 用户名字 的 用户账号状态的模糊查询
     *
     * @param pageNum
     * @param pageSize
     * @param accountName
     * @param isDelete
     * @return
     * @throws Exception
     */
    @GetMapping("/findAccountLikeName")
    @ApiOperation(value = "模糊查询用户")
    @CheckPermission("account:select")
    public JsonResult<PageInfo<Account>> findAccountLikeNameAndIsDelete(
            @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize,
            String accountName, Byte isDelete, String accountType) throws Exception {
        log.info("accountName: " + accountName + ", isDelete: " + isDelete + ", accountType: " + accountType);
        PageInfo<Account> page = accountService.findAccountLikeName(pageNum, pageSize, accountName, isDelete, accountType);
        return JsonResult.build(200, "success", page);
    }


    /**
     * 新增时的重名验证
     *
     * @param accountName
     * @return
     * @throws Exception
     */
    @GetMapping("/checkAccountName/{accountName}")
    @ApiOperation(value = "检查账号是否存在")
    public JsonResult checkAccountName(@PathVariable String accountName) throws Exception {
        Account account = accountService.checkAccountName(accountName);
        if (account != null) {
            if (account.getAccountName().equals(accountName)) {
                return JsonResult.build(500, "此用户名已存在，不可使用", 0);
            } else {
                return JsonResult.build(200, "此用户名可以使用", 1);
            }
        } else {
            return JsonResult.build(200, "此用户名可以使用", 1);
        }
    }

    /**
     * 修改时的重名验证
     *
     * @param accountId
     * @param accountName
     * @return
     * @throws Exception
     */
    @GetMapping("/checkAccountNameAndId/{accountId}/{accountName}")
    @ApiOperation(value = "检查账号是否存在，排除当前的")
    public JsonResult checkAccountNameAndId(@PathVariable Integer accountId, @PathVariable String accountName) throws
            Exception {
        Account account = accountService.selectAccountByNameAndId(accountName, accountId);
        if (account == null) {
            return JsonResult.build(200, "此用户名可以使用", 1);
        } else {
            return JsonResult.build(500, "此用户名已存在，不可使用", 0);
        }
    }

    /**
     * 批量重置用户密码
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @GetMapping("/updatePasswordByIds")
    @ApiOperation(value = "修改用户密码")
    @CheckPermission("account:update")
    public JsonResult<Integer> updatePasswordByIds(int[] ids) throws Exception {
        for (int i = 0; i < ids.length; i++) {
            log.info("================================" + ids[i]);
        }
        ArrayList<Account> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            list.add(new Account(ids[i]));
        }
        int i = accountService.updateAccountPasswordByIds(list);
        if (i > 0) {
            return JsonResult.build(200, "修改成功", i);
        } else {
            return JsonResult.build(500, "修改失败", i);
        }
    }

    /**
     * 获取所有的角色信息，用于对于用户的角色授权
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/getAllRoles")
    @ApiOperation(value = "获取所有角色")
    public JsonResult<List<Role>> getAllRoles(Integer isDelete) throws Exception {
        List<Role> roles = roleService.getAllRoleInfo(isDelete);
        return JsonResult.build(200, "success", roles);
    }

    /**
     * 根据用户 获取用户角色
     *
     * @param accountId
     * @return
     * @throws Exception
     */
    @GetMapping("/getRoleById/{accountId}")
    @ApiOperation(value = "根据用户id获取角色")
    public JsonResult<Set<Integer>> getRoleById(@PathVariable Integer accountId) throws Exception {
        Set<Integer> userRole = userRoleService.getRoleByAccountId(accountId);
        return JsonResult.build(200, "success", userRole);
    }

    /**
     * 用户授权
     *
     * @param accountId
     * @param ids
     * @return
     * @throws Exception
     */
    @PutMapping("/grantRoleByAccountId")
    @ApiOperation(value = "授权角色")
    @CheckPermission("role:update")
    public JsonResult grantRoleByAccountId(int accountId, int[] ids) throws Exception {
        ArrayList<UserRole> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            list.add(new UserRole(accountId, ids[i]));
        }
        int i = userRoleService.addRoleByAccountId(accountId, list);
        if (i > 0) {
            return JsonResult.build(200, "授权成功", i);
        } else {
            return JsonResult.build(500, "授权失败", i);
        }
    }
}
